package cn.googift.recognition.gui.windows;

import cn.googift.crawler.sites.jingdong.recognize.PricePlateAnalysis;
import cn.googift.crawler.util.ImageFileFilter;
import cn.googift.recognition.Recognizer;
import cn.googift.recognition.gui.tools.FileListModel;
import cn.googift.recognition.image.Photo;
import cn.googift.recognition.image.implement.DefaultCharAnalysis;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class FrameMain extends javax.swing.JFrame {
    static final long serialVersionUID = 0;
    private Photo car;

    public class RecognizeThread extends Thread {
        FrameMain parentFrame = null;

        public RecognizeThread(FrameMain parentFrame) {
            this.parentFrame = parentFrame;
        }

        public void run() {
            String recognizedText = "";
            this.parentFrame.recognitionLabel.setText("processing ...");
            int index = this.parentFrame.selectedIndex;
            try {

                PricePlateAnalysis analysis = new PricePlateAnalysis();
                recognizedText = new Recognizer(PricePlateAnalysis.loadBaseChars(), PricePlateAnalysis.getBaseChars(), analysis, new DefaultCharAnalysis(analysis)).recognize(this.parentFrame.car.getBi());
            } catch (Exception ex) {
                ex.printStackTrace();
                this.parentFrame.recognitionLabel.setText("");
                return;
            }
            this.parentFrame.recognitionLabel.setText(recognizedText);
            this.parentFrame.fileListModel.fileList.elementAt(index).recognizedPlate = recognizedText;
        }
    }

    public class LoadImageThread extends Thread {
        FrameMain parentFrame = null;
        String url = null;

        public LoadImageThread(FrameMain parentFrame, String url) {
            this.parentFrame = parentFrame;
            this.url = url;
        }

        public void run() {
            try {
                this.parentFrame.car = new Photo(url);
                this.parentFrame.panelCarContent = this.parentFrame.car.getBi();
//                this.parentFrame.panelCarContent = Photo.linearResizeBi(this.parentFrame.panelCarContent,
//                        this.parentFrame.panelCar.getWidth(),
//                        this.parentFrame.panelCar.getHeight());
                this.parentFrame.panelCar.paint(this.parentFrame.panelCar.getGraphics());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    BufferedImage panelCarContent;

    JFileChooser fileChooser;
    private FileListModel fileListModel;
    int selectedIndex = -1;

    /**
     * Creates new form MainFrame
     */
    public FrameMain() {
        initComponents();

        // init : file chooser
        this.fileChooser = new JFileChooser();
        this.fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        this.fileChooser.setFileFilter(new ImageFileFilter());

        // init : window dimensions and visibility
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int width = this.getWidth();
        int height = this.getHeight();
        this.setLocation((screenSize.width - width) / 2, (screenSize.height - height) / 2);
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        recognitionLabel = new javax.swing.JLabel();
        panelCar = new JPanel() {
            static final long serialVersionUID = 0;

            public void paint(Graphics g) {
                super.paint(g);
                g.drawImage(panelCarContent, 0, 0, null);
            }
        };
        fileListScrollPane = new javax.swing.JScrollPane();
        fileList = new javax.swing.JList();
        recognizeButton = new javax.swing.JButton();
        bottomLine = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        imageMenu = new javax.swing.JMenu();
        openDirectoryItem = new javax.swing.JMenuItem();
        exitItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        aboutItem = new javax.swing.JMenuItem();
        helpItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JavaANPR");
        setResizable(false);
        recognitionLabel.setBackground(new java.awt.Color(0, 0, 0));
        recognitionLabel.setFont(new java.awt.Font("Arial", 0, 24));
        recognitionLabel.setForeground(new java.awt.Color(255, 204, 51));
        recognitionLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        recognitionLabel.setText(null);
        recognitionLabel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        recognitionLabel.setOpaque(true);

        panelCar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        org.jdesktop.layout.GroupLayout panelCarLayout = new org.jdesktop.layout.GroupLayout(panelCar);
        panelCar.setLayout(panelCarLayout);
        panelCarLayout.setHorizontalGroup(
                panelCarLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(0, 585, Short.MAX_VALUE)
        );
        panelCarLayout.setVerticalGroup(
                panelCarLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(0, 477, Short.MAX_VALUE)
        );

        fileListScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        fileListScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        fileList.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
        fileList.setFont(new java.awt.Font("Arial", 0, 11));
        fileList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                fileListValueChanged(evt);
            }
        });

        fileListScrollPane.setViewportView(fileList);

        recognizeButton.setFont(new java.awt.Font("Arial", 0, 11));
        recognizeButton.setText("recognize plate");
        recognizeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recognizeButtonActionPerformed(evt);
            }
        });

        bottomLine.setFont(new java.awt.Font("Arial", 0, 11));
        bottomLine.setText("Copyright (c) 2006 Ondrej Martinsky");

        menuBar.setFont(new java.awt.Font("Arial", 0, 11));
        imageMenu.setText("Image");
        imageMenu.setFont(new java.awt.Font("Arial", 0, 11));
        openDirectoryItem.setFont(new java.awt.Font("Arial", 0, 11));
        openDirectoryItem.setText("Load snapshots from directory");
        openDirectoryItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openDirectoryItemActionPerformed(evt);
            }
        });

        imageMenu.add(openDirectoryItem);

        exitItem.setFont(new java.awt.Font("Arial", 0, 11));
        exitItem.setText("Exit");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });

        imageMenu.add(exitItem);

        menuBar.add(imageMenu);

        helpMenu.setText("Help");
        helpMenu.setFont(new java.awt.Font("Arial", 0, 11));
        helpMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpMenuActionPerformed(evt);
            }
        });

        aboutItem.setFont(new java.awt.Font("Arial", 0, 11));
        aboutItem.setText("About");
        aboutItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutItemActionPerformed(evt);
            }
        });

        helpMenu.add(aboutItem);

        helpItem.setFont(new java.awt.Font("Arial", 0, 11));
        helpItem.setText("Help");
        helpItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpItemActionPerformed(evt);
            }
        });

        helpMenu.add(helpItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, bottomLine, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, panelCar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(fileListScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, recognitionLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                                .add(recognizeButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
                        .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(layout.createSequentialGroup()
                                        .add(fileListScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(recognizeButton)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(recognitionLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 44, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(panelCar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(bottomLine))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void helpMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpMenuActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_helpMenuActionPerformed

    private void helpItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpItemActionPerformed
    }//GEN-LAST:event_helpItemActionPerformed

    private void aboutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutItemActionPerformed
    }//GEN-LAST:event_aboutItemActionPerformed

    private void recognizeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recognizeButtonActionPerformed
        String plate = null;

        // namiesto tohto urobime thread plate = Main.systemLogic.recognize(this.car);
        // thread code start
        new RecognizeThread(this).start();
        // thread code end

//            this.fileListModel.fileList.elementAt(this.selectedIndex).recognizedPlate = plate;
//            this.label.setText(plate);

    }//GEN-LAST:event_recognizeButtonActionPerformed

    private void fileListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_fileListValueChanged
        int selectedNow = this.fileList.getSelectedIndex();

        if (selectedNow != -1 && this.selectedIndex != selectedNow) {
            this.recognitionLabel.setText(this.fileListModel.fileList.elementAt(selectedNow).recognizedPlate);
            this.selectedIndex = selectedNow;
            // proceed selectedNow
            String path = ((FileListModel.FileListModelEntry) this.fileListModel.getElementAt(selectedNow)).fullPath;
            //this.showImage(path);
            new LoadImageThread(this, path).start();
        }
    }//GEN-LAST:event_fileListValueChanged

    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitItemActionPerformed

    private void openDirectoryItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openDirectoryItemActionPerformed
        int returnValue;
        String fileURL;

        this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        this.fileChooser.setDialogTitle("Load snapshots from directory");
        returnValue = this.fileChooser.showOpenDialog((Component) evt.getSource());

        if (returnValue != this.fileChooser.APPROVE_OPTION) return;

        fileURL = this.fileChooser.getSelectedFile().getAbsolutePath();
        loadImageList(fileURL);
        this.fileList.setModel(fileListModel);

    }//GEN-LAST:event_openDirectoryItemActionPerformed

    private void loadImageList(String fileURL) {
        File selectedFile = new File(fileURL);

        this.fileListModel = new FileListModel();
        for (String fileName : selectedFile.list()) {
            if (!ImageFileFilter.accept(fileName)) continue; // not a image
            this.fileListModel.addFileListModelEntry(fileName, selectedFile + File.separator + fileName);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutItem;
    private javax.swing.JLabel bottomLine;
    private javax.swing.JMenuItem exitItem;
    private javax.swing.JList fileList;
    private javax.swing.JScrollPane fileListScrollPane;
    private javax.swing.JMenuItem helpItem;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenu imageMenu;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openDirectoryItem;
    private javax.swing.JPanel panelCar;
    private javax.swing.JLabel recognitionLabel;
    private javax.swing.JButton recognizeButton;
    // End of variables declaration//GEN-END:variables

}
